package com.veiga.sistema.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.SessionFactory;

import com.veiga.sistema.usuario.Usuario;

public class ConexaoHibernateFilter implements Filter{

	private SessionFactory sf;

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest servelFilter, ServletResponse serveltResponse,
			FilterChain chain) throws IOException, ServletException {
		
				try {
					this.sf.getCurrentSession().beginTransaction();
					
					
					
					HttpServletRequest request = (HttpServletRequest) servelFilter;
					
					String url = request.getRequestURI();
					
					Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
					
					if(possuiPermissao(url, usuario)){
						chain.doFilter(servelFilter, serveltResponse); // Permite acesso
					}else{
						// Nao ta logado
						// Pagina requer login
						if(necessitaLogin(url) && usuario == null){
							request.getSession().setAttribute("ultimoURL", url);
							((HttpServletResponse)serveltResponse).sendRedirect("login.jsf");
						}else{
							// Ta logado
							// Nao tem acesso
							((HttpServletResponse)serveltResponse).sendRedirect("home.jsf");
						}
					}

					
					this.sf.getCurrentSession().getTransaction().commit();
					this.sf.getCurrentSession().close();
					
					
				} catch (Throwable ex) {
					
					try {
						if(this.sf.getCurrentSession().getTransaction().isActive()){
							this.sf.getCurrentSession().getTransaction().rollback();
						}
						
						} catch (Throwable t) {
								t.printStackTrace();
						}
					throw new ServletException(ex.getMessage());
					
				}
				
		
					
	}

	private boolean necessitaLogin(String url) {
		if(url.contains("jsf/cadastrotipo"))
			return true;
		return false;
	}

	private boolean possuiPermissao(String url, Usuario usuario) {
		if(usuario != null){
			if(url.contains("jsf/cadastrotipo") && usuario.getNivel() == 2)
				return true;
		}
		if(url.contains("home") || url.contains("login"))
			return true;
		if(url.contains("javax.faces.resource"))
			return true;
		return false;
	}

	@Override
	public void init(FilterConfig conf) throws ServletException {
			this.sf = HibernateUtil.getSession();
	}

		
}
